package com.yang;

import com.google.protobuf.InvalidProtocolBufferException;
import com.yang.output_dir.UserOuterClass;

public class ProtobufExample {
    public static void main(String[] args) {
        // 1. 构造一个 User 对象
        UserOuterClass.User user = UserOuterClass.User.newBuilder()
                .setId(1)
                .setName("Alice")
                .setEmail("alice@example.com")
                .build();

        // 2. 序列化为二进制数据（字节数组）
        byte[] serializedData = user.toByteArray();
        System.out.println("序列化后的数据长度: " + serializedData.length);

        // 3. 反序列化为 User 对象
        try {
            UserOuterClass.User deserializedUser = UserOuterClass.User.parseFrom(serializedData);
            System.out.println("反序列化后的数据：");
            System.out.println("ID: " + deserializedUser.getId());
            System.out.println("Name: " + deserializedUser.getName());
            System.out.println("Email: " + deserializedUser.getEmail());
        } catch (InvalidProtocolBufferException e) {
            System.err.println("反序列化失败: " + e.getMessage());
        }
    }
}
